import {
  Body,
  Controller,
  Get,
  NotFoundException,
  Patch,
  Post,
  Query,
  Res,
  Session,
  UseGuards,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { AuthService } from '../service/auth.service';
import type { Response } from 'express';
import { SignonDto } from '../dto/auth/login-user.dto';
import { FindUserPipe } from '../pipes/user/find-user.pipe';
import { JwtGuard } from '../guards/jwt.guard';
import { FindUserParamDto } from '../dto/user/find-user.dto';

@Controller('auth')
@UsePipes(new ValidationPipe({ transform: true }))
export class AuthController {
  constructor(private authService: AuthService) {}

  // 获取验证码接口
  @Get('captcha')
  createCaptcha(@Session() session, @Res() res: Response) {
    const captcha = this.authService.createCaptcha();
    session.code = captcha.text;
    // 返回图片格式
    res.type('image/svg+xml');
    res.send(captcha.data);
  }

  // 登录接口
  @Post('login')
  async login(@Body() signonDto: SignonDto, @Session() session) {
    if (
      session.code.toLocaleLowerCase() === signonDto.captcha.toLocaleLowerCase()
    ) {
      let data = await this.authService.login(signonDto);
      return {
        status: 200,
        data: Object.assign(data, { message: '登录成功' }),
      };
    } else {
      return { status: 400, data: { message: '验证码错误' } };
    }
  }

  // 获取用户列表
  @Get('users')
  @UseGuards(JwtGuard)
  async adminGetUsers(
    @Query(FindUserPipe) { pageNum, pageSize }: FindUserParamDto,
    @Query('keyword') keyword: string,
  ) {
    let data = await this.authService.adminGetUsers(pageNum, pageSize, keyword);
    return {
      status: 200,
      data,
    };
  }

  // 更新用户权限
  @Patch('user')
  @UseGuards(JwtGuard)
  async adminUpdateUser(
    @Body() { _id, isAdmin }: { _id: string; isAdmin: string },
  ) {
    let updateUser = await this.authService.adminUpdateUser({ _id, isAdmin });
    if (updateUser.acknowledged) {
      return {
        status: 200,
        message: '更新成功',
      };
    } else {
      throw new NotFoundException('更新失败');
    }
  }
}
